package org.linlinjava.litemall.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.admin.vo.LumiereFormulaSpecificationsVO;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LumiereFormulaSpecifications;
import org.linlinjava.litemall.db.domain.LumiereFormulaSpecificationsDataProportioning;
import org.linlinjava.litemall.db.service.LumiereFormulaSpecificationsDataProportioningService;
import org.linlinjava.litemall.db.service.LumiereFormulaSpecificationsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants.LUMIERE_FORMULA_FORMULA_MATERIAL_EXIST;
import static org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants.LUMIERE_FORMULA_FORMULA_SPECIFICATIONS_COUNT_IS_ZERO;
import static org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil.exception;

/**
 * @auth :ply
 * @date 2024/5/17 13:47
 * @Description TODO
 * 管理配方规格管理服务
 */
@Service
@RequiredArgsConstructor
@Transactional
public class AdminLumiereFormulaSpecificationsService {

    private final LumiereFormulaSpecificationsService lumiereFormulaSpecificationsService;

    private final LumiereFormulaSpecificationsDataProportioningService lumiereFormulaSpecificationsDataProportioningService;

    /**
     * 根据查询条件查询配方规格列表
     * @param lumiereFormulaSpecifications 查询条件
     * @param page 当前页数，默认为1
     * @param limit 每页数量，默认为10
     * @return 配方规格列表
     */
    public ResponseUtil.Response listLumiereFormulaSpecifications(LumiereFormulaSpecifications lumiereFormulaSpecifications,Integer page,Integer limit) {
        // 构建查询条件
        LambdaQueryWrapper<LumiereFormulaSpecifications> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(lumiereFormulaSpecifications.getFormulaId())
                .filter(id -> id != 0) // 判断formulaId是否不等于0
                .ifPresent(id -> queryWrapper.eq(LumiereFormulaSpecifications::getFormulaId, id));

        // 执行查询
        IPage<LumiereFormulaSpecifications> lumiereFormulaList = lumiereFormulaSpecificationsService.page(new Page<>(page,limit),queryWrapper);

        // 返回结果
        return ResponseUtil.okPage(lumiereFormulaList);
    }

    /**
     * 根据指定ID获取配方规格详情。
     * @param id 配方ID
     * @return 包含配方规格详情的响应结果
     */
    public ResponseUtil.Response details(Integer id){
        return ResponseUtil.ok(lumiereFormulaSpecificationsService.getById(id));
    }

    /**
     * 添加新的配方规格。
     * @param lumiereFormulaSpecificationsVO 待添加的配方规格对象
     * @return 添加操作的响应结果
     */
    public ResponseUtil.Response addLumiereFormulaSpecifications(LumiereFormulaSpecificationsVO lumiereFormulaSpecificationsVO) {
        //第一个是必须默认
        if(!lumiereFormulaSpecificationsVO.getIsDefault()){
            //是第一个就一定为默认
            long count = lumiereFormulaSpecificationsService.count(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, lumiereFormulaSpecificationsVO.getFormulaId()));
            lumiereFormulaSpecificationsVO.setIsDefault(count==0?true:lumiereFormulaSpecificationsVO.getIsDefault());
        }
        if(lumiereFormulaSpecificationsVO.getIsDefault()){
            LambdaUpdateWrapper<LumiereFormulaSpecifications> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            objectLambdaUpdateWrapper.eq(LumiereFormulaSpecifications::getFormulaId,lumiereFormulaSpecificationsVO.getFormulaId());
            objectLambdaUpdateWrapper.set(LumiereFormulaSpecifications::getIsDefault,0);
            lumiereFormulaSpecificationsService.update(objectLambdaUpdateWrapper);
        }

        //同步第一个
        List<LumiereFormulaSpecifications> formulaSpecifications = lumiereFormulaSpecificationsService.list(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, lumiereFormulaSpecificationsVO.getFormulaId()));
        lumiereFormulaSpecificationsService.save(lumiereFormulaSpecificationsVO);

        if(!lumiereFormulaSpecificationsVO.getSync() || formulaSpecifications.size()==0){
            return ResponseUtil.ok(lumiereFormulaSpecificationsVO.getId());
        }

        List<LumiereFormulaSpecificationsDataProportioning> lumiereFormulaSpecificationsDataProportionings = lumiereFormulaSpecificationsDataProportioningService.list(Wrappers.lambdaQuery(LumiereFormulaSpecificationsDataProportioning.class).eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId, formulaSpecifications.get(0).getId()));
        if(lumiereFormulaSpecificationsDataProportionings.size()==0){
            return ResponseUtil.ok(lumiereFormulaSpecificationsVO.getId());
        }
        for (LumiereFormulaSpecificationsDataProportioning lumiereFormulaSpecificationsDataProportioning : lumiereFormulaSpecificationsDataProportionings) {
            lumiereFormulaSpecificationsDataProportioning.setId(null);
            lumiereFormulaSpecificationsDataProportioning.setFormulaSpecificationsId(lumiereFormulaSpecificationsVO.getId());
            lumiereFormulaSpecificationsDataProportioning.setIsEdit(lumiereFormulaSpecificationsVO.getSync());
        }
        lumiereFormulaSpecificationsDataProportioningService.saveBatch(lumiereFormulaSpecificationsDataProportionings);

        return ResponseUtil.ok(lumiereFormulaSpecificationsVO.getId());
//        if(save){
//            List<Integer> formulaMaterialIds = lumiereFormulaSpecificationsVO.getFormulaMaterialIds();
//            formulaMaterialIds.forEach(ids -> {
//                LumiereFormulaSpecificationsDataProportioning lumiereFormulaSpecificationsDataProportioning = new LumiereFormulaSpecificationsDataProportioning();
//                lumiereFormulaSpecificationsDataProportioning.setFormulaSpecificationsId(lumiereFormulaSpecificationsVO.getId());
//                lumiereFormulaSpecificationsDataProportioning.setFormulaMaterialId(ids);
//                lumiereFormulaSpecificationsDataProportioningService.save(lumiereFormulaSpecificationsDataProportioning);
//            });
//            return ResponseUtil.ok();
//        }else{
//            return ResponseUtil.fail();
//        }
    }

    /**
     * 更新配方规格信息。
     * @param lumiereFormulaSpecifications 待更新的配方规格对象
     * @return 更新操作的响应结果
     */
    public ResponseUtil.Response updateLumiereFormulaSpecifications(LumiereFormulaSpecifications lumiereFormulaSpecifications) {
        //是第一个就一定为默认
        long count = lumiereFormulaSpecificationsService.count(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, lumiereFormulaSpecifications.getFormulaId()));
        if(count==0&&lumiereFormulaSpecifications.getIsDefault()==false){
            throw exception(LUMIERE_FORMULA_FORMULA_SPECIFICATIONS_COUNT_IS_ZERO);
        }
        if(!lumiereFormulaSpecifications.getIsDefault()){
            LumiereFormulaSpecifications one = lumiereFormulaSpecificationsService.getOne(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, lumiereFormulaSpecifications.getFormulaId()).eq(LumiereFormulaSpecifications::getIsDefault, 1));
            if(one.getId().intValue() == lumiereFormulaSpecifications.getId().intValue()){
                throw exception(LUMIERE_FORMULA_FORMULA_SPECIFICATIONS_COUNT_IS_ZERO);
            }
        }
        if(lumiereFormulaSpecifications.getIsDefault()){
            LambdaUpdateWrapper<LumiereFormulaSpecifications> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            objectLambdaUpdateWrapper.eq(LumiereFormulaSpecifications::getFormulaId,lumiereFormulaSpecifications.getFormulaId());
            objectLambdaUpdateWrapper.set(LumiereFormulaSpecifications::getIsDefault,0);
            lumiereFormulaSpecificationsService.update(objectLambdaUpdateWrapper);
        }
        return lumiereFormulaSpecificationsService.updateById(lumiereFormulaSpecifications) ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    /**
     * 根据指定ID删除配方规格。
     * @param id 待删除的路配方规格ID
     * @return 删除操作的响应结果
     */
    public ResponseUtil.Response deleteLumiereFormulaSpecifications(Integer id){
        lumiereFormulaSpecificationsDataProportioningService.remove(new LambdaQueryWrapper<LumiereFormulaSpecificationsDataProportioning>().eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId,id));
        return lumiereFormulaSpecificationsService.removeById(id) ? ResponseUtil.ok() : ResponseUtil.fail();
    }



}
